<template>
  <div class="shopManage">
    <ContentBox title="商品管理" @left="back" :fixed="true" :ostyle="style">
      <template slot="oleft"><van-icon color="#000000" name="arrow-left"/></template>
    </ContentBox>
    <notice :top="$remToPx('0.88')" class="not"></notice>
    <div class="content" v-if="showLoad">
      <van-tabs
        color="#FFD728"
        v-model="showView"
        :scrollspy="true"
        :swipeable="true"
        :animated="true"
        :swipe-threshold="6"
        @change="changeTab"
       >
        <van-tab v-for="(it,index) in list" :key="index" :title="it">
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="loadMore"
            :immediate-check="true"
          >
            <van-cell v-for="(item, index) in goodsList" :key="index" class="order-table">
              <div class="order-list">
                <div class="item-container">
                  <van-image :src="item.image">
                    <template v-slot:loading>
                      <van-loading type="spinner" size="20" />
                    </template>
                    <template v-slot:error></template>
                  </van-image>
                  <div>
                    <div class="ellipsis">
                      <div class="detail">{{item.store_name}}</div>
                      <div class="money">
                        <p class="price"><i>￥</i>{{item.price}}</p>
                      </div>
                    </div>
                    <p class="info">库存: {{item.stock}}</p>
                  </div>
                </div>
                <div class="item-btn">
                  <span class="item-btn-huise" v-if="showView !== 0" @click="targgetShow(item.id, 1)">上架</span>
                  <span class="item-btn-huise" v-if="showView !== 2" @click="targgetShow(item.id, 0)">下架</span>
                  <span class="item-btn-huise" @click="edit(item.id)">编辑</span>
                  <span class="item-btn-huise" @click="delGoods(item.id)">删除</span>
                </div>
              </div>
            </van-cell>
          </van-list>
        </van-tab>
      </van-tabs>
      <div class="silde" @click="tab">
        <h3 class="plus">+</h3>
        <h2 class="title">新建<br/>商品</h2>
      </div>
    </div>

    <div v-else class="main">
      <van-cell-group>
        <van-field v-model="form.store_name" input-align="center" label="商品名称" placeholder="请输入商品名称" />
      </van-cell-group>
      <div class="image">
        <h3 class="public">商品封面图</h3>
        <div class="shop-avater">
          <van-uploader
            v-model="fileList"
            preview-size="40px"
            :max-count="1"
            accept="image/*"
            :after-read="uploadfile"
            :before-read="beforeUpload"
          />
        </div>
        <p class="txt">
          商品图片最多1张
        </p>
      </div>
      <div class="image">
        <h3 class="public">产品轮播图</h3>
        <div class="shop-avater">
          <van-uploader
            v-model="fileShop"
            preview-size="40px"
            multiple
            :max-count="6"
            accept="image/*"
            :after-read="uploadfileshop"
            :before-read="beforeUploadShopImage"
          />
        </div>
        <p class="txt">
          产品轮播图最多6张
        </p>
      </div>
      <van-cell-group>
        <van-field v-model="form.price" input-align="right" label="现价" placeholder="请输入现价" />
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="form.ot_price" input-align="right" label="原价" placeholder="请输入原价" />
      </van-cell-group>
      <van-field
          readonly
          clickable
          label="商品分类"
          :value="shopCategory"
          input-align="center"
          :placeholder="tst"
          @click="showPicker = true"
        />
      <van-cell-group>
        <van-field v-model="form.stock" input-align="right" label="库存" placeholder="请输入库存" />
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="form.plink_number" input-align="right" label="拼团人数" placeholder="请输入拼团人数" />
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="form.plink_price" input-align="right" label="拼团价格" placeholder="请输入拼团价格" />
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="bargain_price" input-align="right" label="砍价总价格" placeholder="请输入砍价总价格" />
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="bargain_people" input-align="right" label="砍价总人数" placeholder="请输入砍价总人数" />
      </van-cell-group>
      <div class="intro">商品简介</div>
      <van-cell-group>
        <van-field
          v-model="form.store_info"
          rows="3"
          class="textarea"
          autosize
          type="textarea"
          placeholder="请输入商品简介"
          show-word-limit
        />
      </van-cell-group>
      <div class="intro">商品描述</div>
      <van-cell-group>
        <van-field
          v-model="form.description"
          rows="3"
          class="textarea"
          autosize
          type="textarea"
          placeholder="请输入商品描述"
          show-word-limit
        />
      </van-cell-group>
      <div class="intro">商品规格</div>
      <van-cell-group>
        <van-field v-model="items[0].value" input-align="right" label="规格名" placeholder="例如: 颜色" />
      </van-cell-group>
      <van-field
        v-model="itemName"
        center
        clearable
        label="规格项"
        placeholder="例如: 红色"
      >
        <van-button slot="button" size="small" type="primary" @click="addItemName">添加规格项</van-button>
      </van-field>
      <div class="tag_box">
        <van-tag class="tag" v-for="(item, index) in tagList" :key="index" closeable size="medium" type="primary" @close="closeTag(index)">{{item}}</van-tag>
      </div>
      <div class="tag_from" v-for="(item, index) in tagList" :key="index">
        <van-cell-group>
          <van-field input-align="right" label="规格名称" :value="item" disabled/>
        </van-cell-group>
        <van-cell-group>
          <van-field v-model="attrs[index].sales" input-align="right" label="库存" placeholder="请输入库存,单位为(0.1)" />
        </van-cell-group>
        <van-cell-group>
          <van-field v-model="attrs[index].cost" input-align="right" label="现价" placeholder="请输入现价" />
        </van-cell-group>
        <van-cell-group>
          <van-field v-model="attrs[index].price" input-align="right" label="原价" placeholder="请输入原价" />
        </van-cell-group>
        <van-cell-group>
          <van-field v-model="attrs[index].pink_price" input-align="right" label="拼团价格" placeholder="请输入拼团价格" />
        </van-cell-group>
        <van-cell title="图片">
          <div slot="default">
            <van-uploader v-model="tagImgNox[index].fileList" :preview-full-image="false" :max-count="1" :before-read="checkfile(index)" :after-read="tagBoxUpload" />
          </div>
        </van-cell>
      </div>
    </div>
    <div class="ensure" v-if="!showLoad">
      <div @click="apply('0')">放入仓库</div>
      <div @click="apply('1')">保存出库</div>
    </div>
    <van-popup
      v-model="showPicker"
      position="bottom"
      :style="{ height: '30%' }"
    >
      <div class="popup_title">
        <span @click="showPicker = false">取消</span>
        <span @click="confirm">确认</span>
      </div>
      <van-checkbox-group v-model="result" class="check_box">
        <van-cell-group>
          <van-cell
            v-for="(item, index) in columns"
            clickable
            :key="index"
            :title="item.name"
            @click="toggle(index)"
          >
            <van-checkbox
              :name="item.id"
              ref="checkboxes"
              slot="right-icon"
            />
          </van-cell>
        </van-cell-group>
      </van-checkbox-group>
    </van-popup>
    <van-overlay :show="loadshow" class="loading" z-index="9999">
      <van-loading size="2.4rem" :vertical="true">上传中...</van-loading>
    </van-overlay>
  </div>
</template>

<script>
import config from '@/config/config'
export default {
  data () {
    return {
      style: {
        background: '#ffffff',
        color: '#000'
      },
      showLoad: true,
      fileList: [],
      fileShop: [],
      form: {
        store_name: '',
        image: '',
        slider_image: [],
        price: '',
        ot_price: '',
        stock: '',
        plink_number: '',
        store_info: '',
        description: '',
        is_show: '',
        cate_id: [],
        plink_price: '',
        is_bargain: 0,
        bargain_price: '',
        bargain_people: ''
      },
      is_bargain: '',
      bargain_price: '',
      bargain_people: '',
      query: {
        page: 1,
        sale: '',
        sell_out: 1,
        warehouse: '',
        trash: '',
        status: ''
      },
      list: ['出售中', '已售罄', '仓库中'],
      formKeys: '',
      formImage: '',
      allow: 0,
      dataList: [],
      columns: [],
      showPicker: false,
      shopCategory: '',
      showView: 0,
      goodsList: [],
      last_page: 100,
      finished: false,
      loading: false,
      pas: {
        page: 1
      },
      result: [],
      tst: '请选择商品分类',
      items: [{
        value: '',
        detail: [],
        attr_set_top: 1,
        attr_image: ''
      }],
      attrs: [],
      tagList: [],
      itemName: '',
      tagImgNox: [],
      loadshow: false,
      isEdit: false,
      editId: '',
      tagFormIndex: ''
    }
  },
  created () {
    if (this.$route.params.type) {
      this.showLoad = false
    }
    this.getAllShopCategory()
    this.getCategoryType()
    this.getGoodsList()
  },
  methods: {
    back () {
      if (this.showLoad) {
        this.$router.go(-1)
      } else {
        this.showLoad = true
      }
    },
    changeTab () {
      this.loading = false
      this.finished = false
      this.pas = {
        page: 1
      }
      this.getGoodsList()
    },
    getAllShopCategory () {
      this.$axios.get('/api/category').then(res => {
        if (res.status === 200) {
          this.dataList = res.data
        }
      })
    },
    getCategoryType () {
      this.$axios.get('/api/storeCategory/categories', this.query).then(res => {
        if (res.status === 200) {
          this.columns = res.data
        }
      })
    },
    onConfirm (value) {
      this.shopCategory = value
      this.dataList.forEach(item => {
        if (item.cate_name === value) {
          this.form.cate_id[0] = item.id
        }
      })
      this.showPicker = false
    },
    tab () {
      this.dataInit()
      this.showLoad = false
      this.isEdit = false
    },
    uploadfile () {
      this.$upload(this.fileList, 'goods').then(res => {
        let arrList = res
        for (let x in arrList) {
          arrList[x] = `${config.api}${arrList[x]}`
        }
        this.form[this.formKeys] = arrList
      })
    },
    uploadfileshop () {
      this.$upload(this.fileShop, 'goods').then(res => {
        let arrList = res
        for (let x in arrList) {
          arrList[x] = `${config.api}${arrList[x]}`
        }
        this.form[this.formImage] = arrList
      })
    },
    beforeUploadShopImage (file) {
      if (!file.type) {
        return false
      }
      this.formImage = 'slider_image'
      return true
    },
    beforeUpload (file) {
      if (!file.type) {
        return false
      }
      this.formKeys = 'image'
      return true
    },
    apply (value) {
      this.form.is_show = value
      Object.keys(this.form).forEach(key => {
        if (this.form[key] === '') {
          this.$dialog({ message: '请把内容填写完整' })
          this.allow++
        }
      })
      if (this.bargain_price !== '' && this.bargain_people !== '') {
        this.is_bargain = 1
        this.form.is_bargain = 1
        this.form.bargain_price = this.bargain_price
        this.form.bargain_people = this.bargain_people
      } else if (this.bargain_price === '' && this.bargain_people === '') {
        this.is_bargain = 0
        this.form.is_bargain = 0
        this.form.bargain_price = ''
        this.form.bargain_people = ''
      } else if (this.bargain_price !== '' || this.bargain_people !== '') {
        this.$dialog({ message: '请填写完整砍价信息' })
        return false
      }
      if (this.items[0].value === '') {
        this.$dialog({ message: '请填写规格名' })
        return false
      }
      if (this.attrs.length <= 0) {
        this.$dialog({ message: '请添加最少一个商品规格项' })
        return false
      }
      for (let x in this.attrs) {
        if (this.attrs[x].cost === '' || this.attrs[x].price === '' || this.attrs[x].sales === '' || this.attrs[x].pic === '' || this.attrs[x].pink_price === '') {
          this.$dialog({ message: '请把规格项内容填写完整' })
          return false
        }
      }
      for (let x in this.attrs) {
        this.items[0].attr_image += this.attrs[x].pic
        if (x < this.attrs.length - 1) {
          this.items[0].attr_image += ','
        }
      }
      if (this.isEdit) {
        this.$axios.put(`/api/merchant/product/${this.editId}`, this.form).then(res => {
          if (res.status === 200) {
            this.addAttr(this.editId).then(res => {
              this.form.is_show === '1' ? this.$dialog({ message: '更新成功,已出库' }) : this.$dialog({ message: '更新成功,已入库' })
              this.form = {}
              this.showLoad = true
              this.showView = 0
              this.pas.page = 1
              this.loading = false
              this.finished = false
              this.dataInit()
              this.getGoodsList()
            })
          } else {
            this.$dialog({ message: res.msg })
          }
        })
      } else if (!this.isEdit) {
        this.$axios.post('/api/merchant/product', this.form).then(res => {
          if (res.status === 200) {
            this.addAttr(res.data.id).then(res => {
              this.form.is_show === '1' ? this.$dialog({ message: '商品出库成功' }) : this.$dialog({ message: '商品放入仓库成功' })
              this.form = {}
              this.showLoad = true
              this.showView = 0
              this.pas.page = 1
              this.loading = false
              this.finished = false
              this.dataInit()
              this.getGoodsList()
            })
          } else {
            this.$dialog({ message: res.msg })
          }
        })
      }
    },
    // 参数初始化
    dataInit () {
      this.form = {
        store_name: '',
        image: '',
        slider_image: [],
        price: '',
        ot_price: '',
        stock: '',
        plink_number: '',
        store_info: '',
        description: '',
        is_show: '',
        cate_id: [],
        plink_price: '',
        is_bargain: 0,
        bargain_price: '',
        bargain_people: ''
      }
      this.is_bargain = 0
      this.bargain_price = ''
      this.bargain_people = ''
      this.tagList = []
      this.items = [{
        value: '',
        detail: [],
        attr_set_top: 1,
        attr_image: ''
      }]
      this.attrs = []
      this.tst = '请选择商品分类'
      this.tagImgNox = []
      this.fileList = []
      this.fileShop = []
      this.result = []
    },
    getGoodsList () {
      if (this.showView === 0) {
        this.pas.sale = 1
      } else if (this.showView === 1) {
        this.pas.sell_out = 1
      } else if (this.showView === 2) {
        this.pas.warehouse = 1
      }
      this.$axios.get('/api/merchant/product', {
        params: this.pas
      }).then(res => {
        if (res.status === 200) {
          this.last_page = res.data.last_page
          this.goodsList = res.data.data
        }
      })
    },
    loadMore () {
      if (this.pas.page >= this.last_page) {
        this.loading = false
        this.finished = true
        return false
      }
      if (this.showView === 0) {
        this.pas.sale = 1
      } else if (this.showView === 1) {
        this.pas.sell_out = 1
      } else if (this.showView === 2) {
        this.pas.warehouse = 1
      }
      this.loading = true
      this.finished = false
      setTimeout(_ => {
        this.pas.page++
        this.$axios.get('/api/merchant/product', {
          params: this.pas
        }).then(res => {
          if (res.status === 200) {
            this.last_page = res.data.last_page
            this.goodsList.concat(res.data.data)
          }
          this.loading = false
          this.finished = true
        })
      })
    },
    targgetShow (id, isShow) {
      this.$axios.put(`/api/merchant/product/${id}`, {
        is_show: isShow
      }).then(res => {
        if (res.status === 200) {
          this.$toast(`${isShow ? '上架成功' : '下架成功'}`)
          this.pas.page = 1
          this.getGoodsList()
        } else {
          this.$tosat(res.msg)
        }
      })
    },
    delGoods (id) {
      this.$axios.delete(`/api/merchant/product/${id}`).then(res => {
        if (res.status === 200) {
          this.$toast('删除成功')
          this.pas.page = 1
          this.getGoodsList()
        } else {
          this.$toast(res.msg)
        }
      })
    },
    toggle (index) {
      this.$refs.checkboxes[index].toggle()
    },
    confirm () {
      this.form.cate_id = this.result
      this.tst = `已选择${this.result.length}个商品分类`
      this.showPicker = false
    },
    closeTag (index) {
      this.tagList.splice(index, 1)
      this.attrs.splice(index, 1)
    },
    tagBoxUpload () {
      // 此时可以自行将文件上传至服务器
      // console.log(this.tagImgNox[index].fileList)
      // if (this.tagImgNox[index].fileList.length === 0 || this.tagImgNox[index].fileList === '' || this.tagImgNox[index].fileList[0].url) {
      //   return
      // }
      this.$upload(this.tagImgNox[this.tagFormIndex].fileList).then(res => {
        let arrList = res
        for (let x in arrList) {
          arrList[x] = `${config.api}${arrList[x]}`
        }
        this.attrs[this.tagFormIndex].pic = arrList[0]
      })
    },
    checkfile (index) {
      this.tagFormIndex = index
    },
    addItemName () {
      if (this.itemName === '') {
        this.$toast('规格项不能为空')
        return false
      }
      if (/^[0-9]+.?[0-9]*$/.test(this.itemName)) {
        this.$toast('规格项不能使用纯数字类型')
        return false
      }
      let obj = {
        detail: {},
        cost: '',
        price: '',
        sales: '',
        pic: '',
        pink_price: ''
      }
      obj.detail[this.items[0].value] = this.itemName
      this.attrs.push(obj)
      this.tagImgNox.push({
        fileList: []
      })
      this.items[0].detail.push(this.itemName)
      if (!this.isEdit) {
        this.tagList.push(this.itemName)
      }
      this.itemName = ''
    },
    addAttr (id) {
      return new Promise(resolve => {
        this.$axios.put(`/api/merchant/product/${id}/attrUpdate`, {
          items: this.items,
          attrs: this.attrs
        }).then(res => {
          if (res.status === 200) {
            resolve(res)
          } else {
            this.$dialog({ message: res.msg })
          }
        })
      })
    },
    edit (id) {
      this.dataInit()
      this.isEdit = true
      this.showLoad = false
      this.editId = id
      this.$axios.get(`/api/merchant/product/${id}`).then(res => {
        if (res.status === 200) {
          this.form = {
            store_name: res.data.product.store_name,
            image: [res.data.product.image],
            slider_image: res.data.product.slider_image,
            price: res.data.product.price,
            ot_price: res.data.product.ot_price,
            stock: res.data.product.stock,
            plink_number: res.data.product.plink_number,
            store_info: res.data.product.store_info,
            description: res.data.product.description,
            is_show: res.data.product.is_show,
            cate_id: res.data.product.cate_id.split(','),
            plink_price: res.data.product.plink_price,
            is_bargain: res.data.product.is_bargain,
            bargain_people: res.data.product.bargain_people,
            bargain_price: res.data.product.bargain_price
          }
          this.is_bargain = res.data.product.is_bargain
          this.bargain_people = res.data.product.bargain_people
          this.bargain_price = res.data.product.bargain_price
          this.fileList.push({ url: res.data.product.image })
          for (let x in res.data.product.slider_image) {
            this.fileShop.push({ url: res.data.product.slider_image[x] })
          }
          for (let x in this.form.cate_id) {
            this.result.push(parseInt(this.form.cate_id[x]))
          }
          this.tst = `已选择${this.form.cate_id.length}个商品分类`
          this.items = [{
            value: res.data.atrr.attr[0].value,
            detail: res.data.atrr.attr[0].detail,
            attr_set_top: 1,
            attr_image: ''
          }]
          this.tagList = res.data.atrr.attr[0].detail
          for (let x in res.data.atrr.value) {
            let obj = {
              detail: res.data.atrr.value[x].detail,
              cost: res.data.atrr.value[x].cost,
              price: res.data.atrr.value[x].price,
              sales: res.data.atrr.value[x].sales,
              pic: res.data.atrr.value[x].pic,
              pink_price: res.data.atrr.value[x].pink_price
            }
            this.attrs.push(obj)
            this.tagImgNox.push({
              fileList: [{ url: res.data.atrr.value[x].pic }]
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
